using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace TST.SharePoint.Shared
{
    public class WSSFieldLookup : FieldLookup
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        public WSSFieldLookup()
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="ID">The ID for the field.</param>
        public WSSFieldLookup(string Id)
            : base(Id)
        {
        }

        private string Escape(string value)
        {
            return Regex.Replace(value, "^[0-9]+;#", "");
        }

        private string EscapeValues(object value)
        {
            if (value is SPFieldLookupValueCollection)
            {
                string result = null;
                SPFieldLookupValueCollection vals = value as SPFieldLookupValueCollection;
                for (int i = 0; i < vals.Count; i++)
                {
                    result += vals[i].LookupValue;
                    if (i < vals.Count - 1)
                        result += ";#";
                }
                return result;
            }
            else
            {
                return Escape(value.ToString());
            }
        }

        public override object GetTypedValue(object value)
        {
            if (value == null)
                return null;
            return EscapeValues(value);
        }

        public override string GetTypedValueAsString(object value)
        {
            if (value == null)
                return null;
            return EscapeValues(value);
        }

        public override string GetTypedValueFormatted(object value)
        {
            if (value == null)
                return null;
            return EscapeValues(value);
        }

    }
}
